﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


namespace test
{
    public class StreamSender
    {
        private const int BufferSize = 1024;
        private const string ServerIp = "192.168.0.100"; 
        private const int ServerPort = 9999; 
        private Socket socket;

        private Queue<byte[]> bytes = new Queue<byte[]>();
        private byte[] buffer;

        public StreamSender(byte[] data)
        {
            buffer = data;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Connect()
        {
            var thread = new Thread(new ThreadStart(ConnectAsync));
            thread.Start();
            //var thread2 = new Thread(new ThreadStart(Update));
            //thread2.Start();
        }

        public void Sending(byte[] msg,string type)
        {
            bytes.Enqueue(msg);
        }
        private void Update()
        {
            while(true)
            {
                if(null != socket && connect)
                {
                   byte[] data = bytes.Dequeue( );
                    if(null != data)
                    {
                        socket.Send(data);
                    }
                }
            }
        }
        bool connect = false;
        private void ConnectAsync()
        {
            try
            {
                socket.BeginConnect(IPAddress.Parse(ServerIp), ServerPort, ConnectCallback, socket);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }

        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                socket.EndConnect(ar);
                Console.WriteLine("Connected to the server.");
                // 这里可以发送和接收消息的代码...  
                connect = true;
                byte[] data = Encoding.Unicode.GetBytes("[msg:" + buffer.Length + "]");
                socket.Send(buffer);


                // 关闭连接  
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
    }
}
